<?php
namespace app\api\controller\v1;
use think\Db;
use app\service\GaodeService;
class Useraddress extends Base
{
	public function _initialize()
	{
		parent::_initialize();
		$this->IsLogin(); //验证登录
	}

	/**
	 * 用户地址保存
	 */
	public function save()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'name' => 'require',
				'mobile' => ['require', 'regex' => '^1((3|4|5|6|7|8|9){1}\d{1})\d{8}$'],
				'address' => 'require',
				'lng' => 'require',
				'lat' => 'require',
				'address_des' => 'require'
			],
			[
				'name.require' => '请填写联系人姓名',
				'mobile.require' => '请填写手机号',
				'mobile.regex' => '手机格式有误',
				'address.require' => '请选择所在地区',
				'lng.require' => '请选择所在地区',
				'lat.require' => '请选择所在地区',
				'address_des.require' => '请填写详细地址'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //根据坐标获取当前省、市、区/县
        //获取高德解地址
        $ni_dili_data = http_curl('https://restapi.amap.com/v3/geocode/regeo?output=json&location='.$params['lng'].','.$params['lat'].'&key='.GaodeService::$web_api_key);
        $ni_dili_data = json_decode($ni_dili_data, true);
        if($ni_dili_data['status'] == 1)
        {
        	//根据行政区编码返查出省、市、区/县
        	$adcode = $ni_dili_data['regeocode']['addressComponent']['adcode'];
        	if(!empty($adcode))
        	{
        		//查询当前区/县
        		$county_info = Db::name('area')->where(['id' => $adcode, 'lev' => 3])->find();
        		//查询当前市
        		$city_info = Db::name('area')->where(['id' => $county_info['pid'], 'lev' => 2])->find();
        		//查询当前省
        		$province_info = Db::name('area')->where(['id' => $city_info['pid'], 'lev' => 1])->find();
        	}
        }
        //基础数据
        $data = [
        	'user_id' => $params['user']['id'],
        	'name' => $params['name'],
        	'mobile' => $params['mobile'],
        	'province' => isset($province_info['id']) ? $province_info['id'] : 0,
        	'city' => isset($city_info['id']) ? $city_info['id'] : 0,
        	'county' => isset($county_info['id']) ? $county_info['id'] : 0,
        	'province_name' => isset($province_info['name']) ? $province_info['name'] : '',
        	'city_name' => isset($city_info['name']) ? $city_info['name'] : '',
        	'county_name' => isset($county_info['name']) ? $county_info['name'] : '',
        	'address' => $params['address'],
        	'address_des' => $params['address_des'],
        	'lng' => $params['lng'],
        	'lat' => $params['lat'],
        	'is_default' => $params['is_default']
        ];
        //启动事务
        Db::startTrans();
        // 默认地址处理
        if($data['is_default'] == 1)
        {
        	Db::name('user_address')->where(['user_id' => $params['user']['id'], 'is_default' => 1])->update(['is_default' => 0]);
        }
        // 添加/编辑
        if(empty($params['id']))
        {
        	$data['add_time'] = time();
        	$data['upd_time'] = time();
        	$user_address_id = Db::name('user_address')->insertGetId($data);
        }else
        {
        	$data['upd_time'] = time();
        	if(Db::name('user_address')->where(['id'=>intval($params['id'])])->update($data))
        	{
        		$user_address_id = $params['id'];
        	}
        }
        // 是否成功
        if(isset($user_address_id) && $user_address_id > 0)
        {
        	//提交事务
        	Db::commit();
        	$result['code'] = 0;
			$result['msg'] = "操作成功";
        }else
        {
        	//回滚事务
        	Db::rollback();
        	$result['code'] = -1;
			$result['msg'] = "操作失败";
        }
        echo json_encode($result);
	}

	/**
	 * 获取地址列表
	 */
	public function lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		//表单验证
		$validate = $this->validate(
			$params,
			[
				'page' => 'require'
			],
			[
				'page.require' => '分页有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $map = [
        	'user_id' => $params['user']['id'],
        	'is_delete_time' => 0
        ];
        $list_data = Db::name('user_address')->where($map)->order('id desc')->limit(($params['page']-1)*10,10)->select();
        if(!empty($list_data))
        {
        	$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "暂无数据";
        }
        echo json_encode($result);
	}

	/**
	 * 获取地址详情
	 */
	public function detail()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		//验证数据
		$validate = $this->validate(
			$params,
			[
			    'id' => 'require'	
			],
			[
				'id.require' => '地址id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询地址信息
        $map = [
        	'id' => $params['id'],
        	'is_delete_time' => 0
        ];
        $info = Db::name('user_address')->field('id,name,mobile,address,address_des,lng,lat,is_default')->where($map)->find();
        if(!empty($info))
        {
        	$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $info;
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "暂无数据";
        }
        echo json_encode($result);
	}

	/**
	 * 设置默认地址
	 */
	public function set_default()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		//验证数据
		$validate = $this->validate(
			$params,
			[
			    'id' => 'require'	
			],
			[
				'id.require' => '地址id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        // 开启事务
        Db::startTrans();
        // 先全部设置为0 再将当前设置为1
        $all_status = Db::name('user_address')->where(['user_id' => $params['user']['id']])->update(['is_default' => 0]);
        $my_status = Db::name('user_address')->where(['user_id' => $params['user']['id'], 'id' => $params['id']])->update(['is_default' => 1]);
        if($all_status !== false && $my_status)
        {
        	// 提交事务
        	Db::commit();
        	$result['code'] = 0;
	        $result['msg'] = "操作成功";
        }else
        {
        	// 回滚事务
        	Db::rollback();
        	$result['code'] = -1;
	        $result['msg'] = "操作失败";
        }
        echo json_encode($result);
	}

	/**
	 * 删除地址
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		//验证数据
		$validate = $this->validate(
			$params,
			[
			    'id' => 'require'	
			],
			[
				'id.require' => '地址id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        // 软删除数据
        $map = ['user_id' => $params['user']['id'], 'id' => $params['id']];
        $data = ['is_delete_time' => time()];
        if(Db::name('user_address')->where($map)->update($data))
        {
        	$result['code'] = 0;
	        $result['msg'] = "操作成功";
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "操作失败";
        }
        echo json_encode($result);
	}
}